<template>
  <div class="dashboard-container">
    <!-- 商品库存柱状图 -->
    <div class="chart-box">
      <h3>商品库存数量统计</h3>
      <div ref="barChart" style="width: 100%; height: 400px;"></div>
    </div>
    
    <!-- 分类数量饼图 -->
    <div class="chart-box">
      <h3>商品分类数量分布</h3>
      <div ref="pieChart" style="width: 100%; height: 400px;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { page as goodsPage } from "@/api/Goods"; 
import { getByCategory } from '@/api/GoodsCategory.js'

export default {
  name: 'GoodsDashboard',
  data() {
    return {
      barChart: null,
      pieChart: null,
      allGoodsData: [],
      categoryList: []
    }
  },
  mounted() {
    this.initBarChart();
    this.initPieChart();
    this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  methods: {
    // 初始化柱状图
    initBarChart() {
      this.barChart = echarts.init(this.$refs.barChart);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        grid: {
          top: '15%',
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: { 
            rotate: 30,
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          name: '数量'
        },
        series: [{
          name: '库存量',
          type: 'bar',
          barWidth: '60%',
          data: [],
          itemStyle: {
            color: (params) => {
              const colors = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'];
              return colors[params.dataIndex % colors.length];
            }
          },
          label: { 
            show: true, 
            position: 'top',
            fontSize: 12
          }
        }]
      };
      this.barChart.setOption(option);
    },

    // 初始化饼图
    initPieChart() {
      this.pieChart = echarts.init(this.$refs.pieChart);
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 20,
          top: 'center',
          textStyle: {
            fontSize: 12
          },
          data: []
        },
        series: [{
          name: '分类数量',
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 1
          },
          label: {
            show: true,
            formatter: '{b|{b}:}\n{c} ({d}%)',
            rich: {
              b: {
                fontSize: 12,
                lineHeight: 20
              }
            }
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          data: []
        }]
      };
      this.pieChart.setOption(option);
    },

    // 获取数据
    async fetchData() {
      try {
        // 获取商品数据
        const goodsRes = await goodsPage({ page: 1, pageSize: 1000 });
        if (goodsRes.data?.code === 200) {
          this.allGoodsData = goodsRes.data.data.records;
          this.updateBarChart();
        }

        // 获取分类数据
        const catRes = await getByCategory();
        if (catRes.data?.code === 200) {
          this.categoryList = catRes.data.data;
          this.updatePieChart();
        }
      } catch (error) {
        console.error('数据加载失败:', error);
      }
    },

    // 更新柱状图
    updateBarChart() {
      const sortedData = [...this.allGoodsData].sort((b, a) => b.quantity - a.quantity);
      const displayData = sortedData.slice(0, 10);
      
      this.barChart.setOption({
        xAxis: { data: displayData.map(item => item.goods) },
        series: [{ data: displayData.map(item => item.quantity) }]
      });
    },

    // 更新饼图
    updatePieChart() {
      if (!this.allGoodsData.length || !this.categoryList.length) return;
      
      // 统计每个分类的商品数量
      const categoryMap = {};
      this.allGoodsData.forEach(item => {
        if (item.category) {
          categoryMap[item.category] = (categoryMap[item.category] || 0) + 1;
        }
      });

      // 准备饼图数据
      const pieData = this.categoryList
        .filter(cat => categoryMap[cat.category] > 0) // 只显示有商品的分类
        .map(cat => ({
          name: cat.category,
          value: categoryMap[cat.category]
        }))
        .sort((a, b) => b.value - a.value); // 按数量降序

      this.pieChart.setOption({
        legend: { 
          data: pieData.map(item => item.name) 
        },
        series: [{
          data: pieData
        }]
      });
    },

    // 窗口大小变化时重绘图表
    handleResize() {
      this.barChart?.resize();
      this.pieChart?.resize();
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.barChart?.dispose();
    this.pieChart?.dispose();
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-box {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-box h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}
</style>